//
//  searchViewVC.swift
//  movieInfo
//
//  Created by zhangkai on 2023/5/14.
//

import UIKit

class searchViewVC: BaseVC,UITableViewDelegate,UITableViewDataSource {
    
    var tableView:UITableView!
    
    var one:[Movie] = []
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        view.addSubview(tableView)
//
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        tableView.snp.makeConstraints { make in
//            make.top.equalToSuperview().offset(20)
            make.top.equalToSuperview()
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.bottom.equalToSuperview()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        view.backgroundColor = .white
        
        
        
//        navigationController?.navigationBar.prefersLargeTitles = true
        title = "Search"
        
        
        let searchController = UISearchController()
        searchController.searchBar.delegate = self
        searchController.searchBar.placeholder = "Search a Movie"
        searchController.obscuresBackgroundDuringPresentation = false
        navigationItem.searchController = searchController
 
        
        
        tableView = UITableView(frame: CGRectZero, style: .plain)
        tableView.register(searchViewVCCell.self, forCellReuseIdentifier: "searchViewVCCell")

        tableView.backgroundColor = .secondarySystemBackground
        tableView.rowHeight = 190
        tableView.estimatedSectionFooterHeight = 0.01
        tableView.estimatedSectionHeaderHeight = 0.01
        tableView.tableFooterView = UIView()
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        tableView.delegate = self
        tableView.dataSource = self
//        tableView.isHidden = true

//        tableView.contentInset = UIEdgeInsets(top: -10, left: 0, bottom: -10, right: 0)
        
        
 
        
       
        
    }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return self.one.count
        
       
   }
   
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell:searchViewVCCell = tableView.dequeueReusableCell(withIdentifier: "searchViewVCCell") as? searchViewVCCell ?? searchViewVCCell()
        cell.selectionStyle = .none
//        cell.nameLabel.text = "hah"
        
        
        if let path = self.one[indexPath.row].posterPath {
            cell.img.downloadImage(fromPath: path)
        }
        cell.nameLabel.text = self.one[indexPath.row].title ?? ""
        cell.stattLabel.text = "\(self.one[indexPath.row].voteAverage ?? 0.0)"
        cell.infoLabel.text = self.one[indexPath.row].overview ?? ""
        
        
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let movieInfo = self.one[indexPath.row]
        let destVC = ViewControllerInfoVC()
        destVC.model = movieInfo
        self.navigationController?.pushViewController(destVC, animated: true)
        
        
    }

}

extension searchViewVC: UISearchBarDelegate {
    
    func stringByAddingPercentEncoding(str:String) -> String? {
        let unreserved = "-._~/?"
        let allowed = NSMutableCharacterSet.alphanumeric()
        allowed.addCharacters(in: unreserved)
        return str.addingPercentEncoding(withAllowedCharacters: allowed as CharacterSet)
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        guard let filter = searchBar.text, !filter.isEmpty else {
            self.resignFirstResponder()
            return
        }

        if let filteredString = stringByAddingPercentEncoding(str: filter) {
            let url = MMNetWork.shared.getSearchURL(query: filteredString, page: 1)
       
            MMNetWork.shared.fetchData(urlString: url, castType: [Movie].self, keyPath: "results") { result in
                switch result {
                case .success(let movies):
                    
                    self.one = movies
                    DispatchQueue.main.async {
                        self.tableView.reloadData()
                    }
    //                completed(.success(movies))
                    break
                case .failure(let error):
    //                completed(.failure(error))
                    
                    break
                }
            }
        }
        
//        }
    }
    
    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        self.one.removeAll()
        self.tableView.reloadData()
        self.resignFirstResponder()
    }
}


class searchViewVCCell:UITableViewCell{
    var img = MIImageView(frame: CGRect(x: 0, y: 0, width: 120, height: 180))
    var nameLabel:UILabel!
    var stattImg = UIImageView()
    var stattLabel = UILabel()
    var infoLabel = UILabel()
    
    
    
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        contentView.addSubview(img)
        img.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(10)
            make.top.equalToSuperview()
            make.width.equalTo(120)
            make.height.equalTo(180)
        }
        img.layer.masksToBounds = true
        img.contentMode = .scaleAspectFill
        
        nameLabel = UILabel()
        nameLabel.text = "N/AN/AN/AN/A"
        nameLabel.numberOfLines = 2
        nameLabel.textColor = .black
        nameLabel.font = UIFont.boldSystemFont(ofSize: 16)
        contentView.addSubview(nameLabel)
        nameLabel.snp.makeConstraints { make in
            make.left.equalTo(img.snp.right).offset(8)
            make.right.equalToSuperview().offset(-8)
            make.top.equalTo(img.snp.top).offset(18)
        }
        
        stattImg.image = UIImage(named: "xingxing")
        contentView.addSubview(stattImg)
        stattImg.snp.makeConstraints { make in
            make.left.equalTo(img.snp.right).offset(8)
            make.top.equalTo(nameLabel.snp.bottom).offset(15)
            make.width.equalTo(15)
            make.height.equalTo(15)
        }

        stattLabel.text = "N/A"
        stattLabel.textColor = .darkText
        stattLabel.font = UIFont.boldSystemFont(ofSize: 12)
        contentView.addSubview(stattLabel)
        stattLabel.snp.makeConstraints { make in
            make.centerY.equalTo(stattImg)
            make.left.equalTo(stattImg.snp.right)

        }


        infoLabel.text = "N/A"
        infoLabel.numberOfLines = 4
        infoLabel.textColor = .black
        infoLabel.font = UIFont.boldSystemFont(ofSize: 16)
        contentView.addSubview(infoLabel)
        infoLabel.snp.makeConstraints { make in
            make.left.equalTo(img.snp.right).offset(8)
            make.right.equalToSuperview().offset(-8)
            make.top.equalTo(stattLabel.snp.bottom).offset(8)
        }
//
        
        
        
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    
    
    
}
